<?php

namespace common\logics;

use Yii;
use common\helpers\ArrayHelper;
use common\helpers\Url;

/**
 * 订单逻辑显示模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class ShopOrderLogic extends \common\models\shop\ShopOrder {

    /**
     * 订单操作类型
     * @var string
     */
    const HANDLE_CANCEL = 'cancel';
    const HANDLE_RECEIVE = 'receive';

    /**
     * @inheritdoc
     */
    public function getStatusData() {
        $code = $this->status;
        $label = strtolower(static::markLabel('status', $code, false));
        $text = '';

        if ($code == static::STATUS_DEFAULT || $code == static::STATUS_ACTIVE) {
            if ($this->getCountdown() > 0) {
                //未超时，显示待付款
                $text = '待付款';
            } else {
                //已超时
                $text = '已超时';
            }
        } elseif ($code == static::STATUS_PAID) {
            //未超时，显示待付款
            if ($this->getIsPay()) {
                $text = '待发货';
            } else {
                $text = '等待支付结果';
                //todo 查询订单支付结果
            }
        } elseif ($code == static::STATUS_SHIP) {
            $text = '已发货';
            if ($this->getCountdown() > 0) {
                //未超时，显示待付款
                $text = '待付款';
            } else {
                //已超时
                $text = '已超时';
            }
        }

        return [
            'code' => $this->status,
            'label' => $label,
            'text' => $this->statusText,
        ];
    }

    /**
     * @inheritdoc
     */
    public function getBtnCancel() {
        if ($this->canCancel) {
            return [
                'type' => 'default',
                'text' => '取消订单',
            ];
        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getBtnUpdate() {
        if ($this->canCancel) {
            return [
                'type' => 'default',
                'text' => '修改信息',
            ];
        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getBtnPay() {
        if (!$this->isExpired && $this->canCancel) {
            return [
                'type' => 'warning',
                'text' => '支付',
            ];
        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getBtnReceive() {
        if ($this->isPay && $this->status == static::STATUS_SHIP) {
            return [
                'type' => 'warning',
                'text' => '确认收货',
            ];
        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getBtnEvaluate() {
//        if ($this->isPay && $this->status == static::STATUS_COMPLETE) {
//            return [
//                'type' => 'warning',
//                'text' => '评价',
//            ];
//        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getBtnService() {
//        if ($this->isPay && $this->status <= static::STATUS_COMPLETE) {
//            return [
//                'type' => 'warning',
//                'text' => '客服',
//            ];
//        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getHandle() {
        $buttonTags = [
            'cancel',
            //'update',
            'pay',
            'receive',
            'evaluate',
            'service',
        ];
        $handles = [];
        foreach ($buttonTags as $name) {
            $method = 'getBtn' . ucfirst($name);
            if (!method_exists($this, $method)) {
                continue;
            }
            $button = $this->$method();
            if (!empty($button)) {
                $handles[$name] = $button;
            }
        }
        if (empty($handles)) {
            return null;
        }
        return $handles;
    }

    /**
     * @inheritdoc
     */
    public function getStatusText() {
        if ($this->status == static::STATUS_CANCEL) {
            return '已取消';
        } elseif ($this->status == static::STATUS_DEFAULT || $this->status == static::STATUS_ACTIVE) {
            return '等待付款';
        } elseif ($this->status == static::STATUS_PAID) {
            return '已付款';
        } elseif ($this->status == static::STATUS_SHIP) {
            return '待收货';
        } elseif ($this->status == static::STATUS_COMPLETE) {
            return '已收货';
        } elseif ($this->status == static::STATUS_SUCCESS) {
            return '已完成';
        }
        return '';
    }

    /**
     * @inheritdoc
     */
    public function getMark() {
        $lines = [];
        if ($this->status == static::STATUS_CANCEL) {
            $lines = ['订单超时或者交易已关闭'];
        } elseif ($this->status == static::STATUS_DEFAULT || $this->status == static::STATUS_ACTIVE) {
            $countdown = date('m月d日H点i分', $this->created_at + static::EXPIRED_DURTION);
            if ($countdown > 0) {
                $lines = ['请在 ' . $countdown . ' 前完成支付'];
            } else {
                $lines = ['订单超时，即将关闭'];
            }
        } elseif ($this->status == static::STATUS_PAID) {
            $lines = ['等待商家发货'];
        } elseif ($this->status == static::STATUS_SHIP) {
            if ($this->express) {
                $lines = ['物流公司：' . $this->express->name, '物流单号：' . $this->express_code];
            } else {
                $lines = ['商家已发货暂无物流信息'];
            }
        } elseif ($this->status > static::STATUS_SHIP) {
            if ($this->express) {
                $lines = ['物流公司：' . $this->express->name, '物流单号：' . $this->express_code];
            } else {
                $lines = [''];
            }
        }
        return $lines;
    }

    /**
     * @inheritdoc
     */
    public function getLink() {
        return Url::weblink('order/view/{id}', [
            'id' => $this->id
        ]);
    }

    /**
     * 判断当前订单是否可以取消
     * @inheritdoc
     */
    public function canCancel() {
        if ($this->isPay) {
            return false;
        }
        if ($this->status == static::STATUS_DEFAULT || $this->status == static::STATUS_ACTIVE) {
            return true;
        }
        return false;
    }

    /**
     * 判断当前订单是否可以确认收货
     * @inheritdoc
     */
    public function canReceive() {
        if ($this->isPay && $this->status == static::STATUS_SHIP) {
            return true;
        }
        return false;
    }

    public function setStatusByHandler($handle) {
        if ($handle == static::HANDLE_CANCEL) {
            $this->status = static::STATUS_CANCEL;
        } elseif ($handle == static::HANDLE_RECEIVE) {
            $this->status = static::STATUS_RECEIVED;
        }
    }

    public static function groupFormat($data, $extras = []) {
        if (empty($data)) {
            return [];
        }
        $extrasData = ArrayHelper::map($extras, 'product_id', 'price');
        $result = [];
        foreach ($data as $item) {
            if (!isset($result[$item->product_id])) {
                $_extras = ArrayHelper::getValue($extrasData, $item->product_id, 0);
                $result[$item->product_id] = [
                    'id' => $item->product_id,
                    'name' => $item->name,
                    'thumb' => $item->thumb,
                    'amount' => 0,
                    'total' => 0,
                    'extras' => $_extras * 1,
                    'goods' => [],
                ];
            }
            $result[$item->product_id]['amount'] += $item->amount;
            $result[$item->product_id]['total'] += $item->goods_number;
            $result[$item->product_id]['goods'][] = [
                'id' => $item->goods_id,
                'sku' => $item->goods_name,
                'price' => $item->goods_price,
                'discount' => $item->goods_discount,
                'num' => $item->goods_number,
                "code" => $item->goods_code,
            ];
        }
        return array_values($result);
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'id',
            'order_no',
            'goods',
            'amount',
            'discount',
            'pay' => 'price',
            'order_time' => function() {
                return date('Y-m-d H:i', $this->created_at);
            },
            'status_text' => 'statusText',
            'mark',
            'handle',
            'express_code',
            'express',
            'link',
        ];
    }

}
